<template>
  <div class="flex flex-col w-full h-full">
    <n-grid :x-gap="24">
      <n-grid-item span="24">
        <n-grid x-gap="10">
          <n-grid-item :span="24">
            <n-form-item label="提示词模式选择" path="resourceId">
              <n-select
                v-model:value="props.storyPaintConfig.promptType"
                :options="promptTypeOptions"
                :render-label="renderLabel">
              </n-select>
            </n-form-item>
          </n-grid-item>
          <n-grid-item :span="24">
            <n-form :model="props.storyPaintConfig" ref="formRef">
              <n-form-item label="绘画资源选择" path="resourceId">
                <n-select
                  v-model:value="props.storyPaintConfig.resourceId"
                  :options="resourceOption"
                  @update:value="resourceSelect"
                  :render-label="renderLabel">
                </n-select>
                <n-tooltip>
                  <template #trigger>
                    <n-button type="primary" @click="loadConfig" style="margin-left:5px; ">刷新
                      <template #icon>
                        <n-icon>
                          <SyncCircleOutline/>
                        </n-icon>
                      </template>
                    </n-button>
                  </template>
                  <span>刷新资源</span>
                </n-tooltip>
              </n-form-item>
            </n-form>
          </n-grid-item>
        </n-grid>
        <n-scrollbar trigger="none" :style="{ height: `${clientHeight - 320}px`}">
          <FooocusSetting
            style="margin-right: 15px;"
            :resourceId="props.storyPaintConfig.resourceId"
            :paintEngineConfig="props.storyPaintConfig.paintEngineConfig"
            v-if="props.storyPaintConfig?.paintType === 'Fooocus'"></FooocusSetting>
          <SdText2ImgSetting
              model="novel"
            style="margin-right: 15px;"
            :resourceId="props.storyPaintConfig.resourceId"
                             :paintEngineConfig="props.storyPaintConfig.paintEngineConfig"
                             v-if="props.storyPaintConfig?.paintType==='SD'"></SdText2ImgSetting>
          <MjSetting
            model="novel"
            style="margin-right: 15px;"
            :paintEngineConfig="props.storyPaintConfig.paintEngineConfig"
                     v-if="props.storyPaintConfig?.paintType==='MJ'"></MjSetting>
        </n-scrollbar>
      </n-grid-item>
    </n-grid>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {useMessage} from 'naive-ui';
import {resourceController} from '@/api/resource/resourceController.api'
import {storyController} from '@/api/story/story.api'
// @ts-ignore
import fileFunction from "@/libs/globalFunction/file"
import SdText2ImgSetting from "@/views/pages/create/components/sdtext2ImgSetting.vue"
import {SyncCircleOutline} from "@vicons/ionicons5"
import MjSetting from "@/views/pages/create/components/mjSetting.vue";
import {storeToRefs} from "pinia";
import {useSystemStore} from "@/store/modules/useSystemStore";
import FooocusSetting from "@/views/pages/create/components/fooocusSetting.vue";

const resourceOption = ref([])


const promptTypeOptions = ref([{
  label: '结构化提示词',
  value: 'easy'
} ])

// const promptTypeOptions = ref([{
//   label: '结构化提示词',
//   value: 'easy'
// }, {
//   label: '高手模式(暂未开放)',
//   value: 'normal',
// }])

const selectedResource = ref("")
const selectedResourceOption = ref({
  label: '',
  value: '',
  type: ''
})

const formRef: any = ref(null);
const message = useMessage();

const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

const props = defineProps({
  story: {
    type: Object,
    default: () => {
      return {}
    }
  },
  storyPaintConfig: {
    type: Object,
    required: true
  }
})

/***
 * 获取绘画资源
 */
const getResourceInfo = async () => {
  try {
    const res = await resourceController.getSDResource('ALL');
    if (res.code === 200) {
      res.data.forEach((item: any) => {
        // @ts-ignore
        resourceOption.value.push({
          label: item.resourceName,
          value: item.id,
          type: item.type,
        });
      });
    } else {
      message.error(res.msg);
    }
  } catch (error) {
    // 处理错误
    console.error(error);
  }
}


// 选中资源后
const resourceSelect = (value: string, option: any) => {
  if (selectedResourceOption.value.type != option.type) {
    initPaintEngineConfig(option.type)
  }
  props.storyPaintConfig.paintType = option.type
}


const initPaintEngineConfig = (engineType: string) => {
  if (engineType == 'Fooocus') {

    props.storyPaintConfig.paintEngineConfig = {
      resourceId:'',
      prompt: '',
      negative_prompt: '',
      style_selections: [
        "Fooocus V2",
        "Fooocus Enhance",
        "Fooocus Sharp"
      ],
      performance_selection: 'Extreme Speed',
      aspect_ratios_selection: '1152*896',
      image_number: 1,
      image_seed: -1,
      sharpness: 2,
      guidance_scale: 4,
      base_model_name: 'animaPencilXL_v100.safetensors',
      refiner_model_name: '',
      refiner_switch: 0.5,
      loras: [{
        model_name: "sd_xl_offset_example-lora_1.0.safetensors",
        weight: 0.1
      }, {
        model_name: "",
        weight: 1
      }, {
        model_name: "",
        weight: 1
      }, {
        model_name: "",
        weight: 1
      }],
      advanced_params: {
        adaptive_cfg: 7,
        adm_scaler_end: 0.3,
        adm_scaler_negative: 0.8,
        adm_scaler_positive: 1.5,
        canny_high_threshold: 128,
        canny_low_threshold: 64,
        controlnet_softness: 0.25,
        debugging_cn_preprocessor: false,
        debugging_inpaint_preprocessor: false,
        disable_intermediate_results: false,
        disable_preview: false,
        disable_seed_increment: false,
        freeu_b1: 1.01,
        freeu_b2: 1.02,
        freeu_enabled: false,
        freeu_s1: 0.99,
        freeu_s2: 0.95,
        inpaint_disable_initial_latent: false,
        inpaint_engine: "v1",
        inpaint_erode_or_dilate: 0,
        inpaint_mask_upload_checkbox: false,
        inpaint_respective_field: 1,
        inpaint_strength: 1,
        invert_mask_checkbox: false,
        mixing_image_prompt_and_inpaint: false,
        mixing_image_prompt_and_vary_upscale: false,
        overwrite_height: -1,
        overwrite_step: -1,
        overwrite_switch: -1,
        overwrite_upscale_strength: -1,
        overwrite_vary_strength: -1,
        overwrite_width: -1,
        refiner_swap_method: "joint",
        sampler_name: "dpmpp_2m_sde_gpu",
        scheduler_name: "karras",
        skipping_cn_preprocessor: false
      },
      require_base64: true,
      async_process: false,
    }
  } else if (engineType == 'SD') {
    props.storyPaintConfig.paintEngineConfig = {
      defaultPrompt: '',
      defaultNegativePrompt: 'multiple breasts, (mutated hands and fingers:1.5 ), (long body :1.3), (mutation, poorly drawn :1.2) , black-white, bad anatomy, liquid body, liquid tongue, disfigured, malformed, mutated, anatomical nonsense, text font ui, error, malformed hands, long neck, blurred, lowers, lowres, bad anatomy, bad proportions, bad shadow, uncoordinated body, unnatural body, fused breasts, bad breasts, huge breasts, poorly drawn breasts, extra breasts, liquid breasts, heavy breasts, missing breasts, huge haunch, huge thighs, huge calf, bad hands, fused hand, missing hand, disappearing arms, disappearing thigh, disappearing calf, disappearing legs, fused ears, bad ears, poorly drawn ears, extra ears, liquid ears, heavy ears, missing ears, fused animal ears, bad animal ears, poorly drawn animal ears, extra animal ears, liquid animal ears, heavy animal ears, missing animal ears, text, ui, error, missing fingers, missing limb, fused fingers, one hand with more than 5 fingers, one hand with less than 5 fingers, one hand with more than 5 digit, one hand with less than 5 digit, extra digit, fewer digits, fused digit, missing digit, bad digit, liquid digit, colorful tongue, black tongue, cropped, watermark, username, blurry, JPEG artifacts, signature, 3D, 3D game, 3D game scene, 3D character, malformed feet, extra feet, bad feet, poorly drawn feet, fused feet, missing feet, extra shoes, bad shoes, fused shoes, more than two shoes, poorly drawn shoes, bad gloves, poorly drawn gloves, fused gloves, bad cum, poorly drawn cum, fused cum, bad hairs, poorly drawn hairs, fused hairs, big muscles, ugly, bad face, fused face, poorly drawn face, cloned face, big face, long face, bad eyes, fused eyes poorly drawn eyes, extra eyes, malformed limbs, more than 2 nipples, missing nipples, different nipples, fused nipples, bad nipples, poorly drawn nipples, black nipples, colorful nipples, gross proportions. short arm, (((missing arms))), missing thighs, missing calf, missing legs, mutation, duplicate, morbid, mutilated, poorly drawn hands, more than 1 left hand, more than 1 right hand, deformed, (blurry), disfigured, missing legs, extra arms, extra thighs, more than 2 thighs, extra calf, fused calf, extra legs, bad knee, extra knee, more than 2 legs, bad tails, bad mouth, fused mouth, poorly drawn mouth, bad tongue, tongue within mouth, too long tongue, black tongue, big mouth, cracked mouth, bad mouth, dirty face, dirty teeth, dirty pantie, fused pantie, poorly drawn pantie, fused cloth, poorly drawn cloth, bad pantie, yellow teeth, thick lips, bad cameltoe, colorful cameltoe, bad asshole, poorly drawn asshole, fused asshole, missing asshole, bad anus, bad pussy, bad crotch, bad crotch seam, fused anus, fused pussy, fused anus, fused crotch, poorly drawn crotch, fused seam, poorly drawn anus, poorly drawn pussy, poorly drawn crotch, poorly drawn crotch seam, bad thigh gap, missing thigh gap, fused thigh gap, liquid thigh gap, poorly drawn thigh gap, poorly drawn anus, bad collarbone, fused collarbone, missing collarbone, liquid collarbone, strong girl, obesity, worst quality, low quality, normal quality, liquid tentacles, bad tentacles, poorly drawn tentacles, split tentacles, fused tentacles, missing clit, bad clit, fused clit, colorful clit, black clit, liquid clit, QR code, bar code, censored, safety panties, safety knickers, beard, furry ,pony, pubic hair, mosaic, excrement, faeces, shit, futa, testis',
      defaultSeed: -1,
      defaultSamplerName: 'Euler a',
      defaultBatchSize: 1,
      defaultSteps: 20,
      defaultWidth: 512,
      defaultHeight: 512,
      promptEn: '',
      defaultCfgScale: 7,
      savePath: '',
      defaultScheduler : 'Automatic',
      defaultRestoreFaces: false,
      defaultEnableHr: false,
      defaultHrUpscaler: 'R-ESRGAN 4x+',
      defaultHrScale: 2.0,
      defaultDenoisingStrength: 0.5,
      defaultHrSecondPassSteps: 8
    }
  } else if (engineType == 'MJ') {
    props.storyPaintConfig.paintEngineConfig = {
      ar: '4:3',
      model: 'MJv6',
      quality: 'high',
      chaos: 0,
      mode: '普通',
      base64: '',
      prompt: '',
      no: '',
      plotMode: '2',
      command: '',
      resourceId: '',
      enableReferencePic: true,
      botType: 'mjbot',
      crefValue: 60,
      srefValue: 100,
      srefImage1Url:'',
      srefImage2Url:'',
      srefImage3Url:'',
      iw: 0.5
    }
  }
}


const renderLabel = (option: any) => {
  if (option.type == null || option.type.length == 0) {
    return option.label
  }
  return option.label + ' 【类型:' + option.type + '】'
}


onMounted(async () => {
  await getResourceInfo()
})

</script>
